import { View, Text, Input, Button } from '@tarojs/components'
import { useState, useEffect } from 'react'
import Taro from '@tarojs/taro'
import api from '../../axios/loginaxios/request'
import { useAuth } from '../../contexts'
import './phone-login.scss'

export default function PhoneLogin() {
    const { login } = useAuth()
    const [phoneNumber, setPhoneNumber] = useState('')
    const [verifyCode, setVerifyCode] = useState('')
    const [countdown, setCountdown] = useState(0)
    const [isLoading, setIsLoading] = useState(false)
    const [userOpenId, setUserOpenId] = useState('')

    // 微信订阅消息模板ID
    const TEMPLATE_ID = 'xHtBOzfkOpgu36ZXRE78kQha3IsQCbZ07AL87mMHQpA'

    // 倒计时效果
    useEffect(() => {
        let timer: NodeJS.Timeout
        if (countdown > 0) {
            timer = setTimeout(() => {
                setCountdown(countdown - 1)
            }, 1000)
        }
        return () => clearTimeout(timer)
    }, [countdown])

    // 获取用户openid
    useEffect(() => {
        getUserOpenId()
    }, [])

    // 获取用户openid
    const getUserOpenId = async () => {
        try {
            // 先检查缓存的openid是否有效
            const cachedOpenId = Taro.getStorageSync('openid')
            const cachedToken = Taro.getStorageSync('token')

            // 如果缓存的是模拟openid，清除缓存
            if (cachedOpenId && cachedOpenId.startsWith('mock_')) {
                console.log('发现模拟openid，清除缓存:', cachedOpenId)
                Taro.removeStorageSync('openid')
                Taro.removeStorageSync('token')
            } else if (cachedOpenId && cachedToken && cachedOpenId.length === 28) {
                setUserOpenId(cachedOpenId)
                console.log('使用缓存的真实openid:', cachedOpenId)
                return
            }

            // 微信登录获取code
            const loginRes = await Taro.login()
            if (loginRes.code) {
                console.log('微信登录code:', loginRes.code)

                // 调用后端接口获取真实openid
                try {
                    console.log('正在调用微信登录接口...')
                    const response: any = await api.post('/auth/wechat-login', {
                        code: loginRes.code,
                        agreeProtocol: true
                    })

                    console.log('微信登录接口响应:', response)

                    if (response.success && response.userInfo && response.userInfo.openid) {
                        const realOpenId = response.userInfo.openid
                        console.log('✅ 获取到真实openid:', realOpenId, '长度:', realOpenId.length)

                        // 验证openid格式
                        if (realOpenId.length === 28 && !realOpenId.startsWith('mock_')) {
                            setUserOpenId(realOpenId)
                            Taro.setStorageSync('openid', realOpenId)
                            Taro.setStorageSync('token', response.token)
                            console.log('✅ 真实openid已缓存')
                        } else {
                            console.error('❌ 获取的openid格式不正确:', realOpenId)
                            setUserOpenId('')
                        }
                    } else {
                        console.error('❌ 微信登录失败:', response.message || '响应格式不正确')
                        setUserOpenId('')
                    }
                } catch (error) {
                    console.error('❌ 调用微信登录接口失败:', error)
                    setUserOpenId('')
                }
            }
        } catch (error) {
            console.error('获取openid失败:', error)
            setUserOpenId('')
        }
    }

    // 请求订阅消息权限
    const requestSubscribePermission = (): Promise<boolean> => {
        return new Promise((resolve) => {
            Taro.requestSubscribeMessage({
                tmplIds: [TEMPLATE_ID],
                success: (res) => {
                    if (res[TEMPLATE_ID] === 'accept') {
                        console.log('用户同意接收订阅消息')
                        resolve(true)
                    } else {
                        console.log('用户拒绝接收订阅消息')
                        resolve(false)
                    }
                },
                fail: (err) => {
                    console.error('订阅消息权限请求失败:', err)
                    resolve(false)
                }
            } as any)
        })
    }

    // 验证手机号格式
    const validatePhone = (phone: string) => {
        const phoneRegex = /^1[3-9]\d{9}$/
        return phoneRegex.test(phone)
    }

    // 处理手机号输入
    const handlePhoneInput = (e) => {
        const { value } = e.detail
        // 只保留数字，最多11位
        const cleanValue = value.replace(/\D/g, '').slice(0, 11)
        setPhoneNumber(cleanValue)
    }

    // 处理验证码输入
    const handleCodeInput = (e) => {
        const { value } = e.detail
        // 只保留数字，最多6位
        const cleanValue = value.replace(/\D/g, '').slice(0, 6)
        setVerifyCode(cleanValue)
    }

    // 发送验证码
    const handleSendCode = async () => {
        if (!validatePhone(phoneNumber)) {
            Taro.showToast({
                title: '请输入正确的手机号',
                icon: 'none'
            })
            return
        }

        if (countdown > 0) {
            return
        }

        try {
            setIsLoading(true)

            // 1. 先请求订阅消息权限
            let hasSubscribePermission = false
            if (userOpenId) {
                hasSubscribePermission = await requestSubscribePermission()

                if (!hasSubscribePermission) {
                    // 用户拒绝授权，询问是否继续使用模拟模式
                    const modalRes = await Taro.showModal({
                        title: '提示',
                        content: '您拒绝了微信通知权限，验证码将通过其他方式发送，是否继续？',
                        confirmText: '继续',
                        cancelText: '重新授权'
                    })

                    if (!modalRes.confirm) {
                        // 用户选择重新授权
                        setIsLoading(false)
                        return
                    }
                }
            }

            // 2. 调用发送验证码接口
            const requestData: any = {
                phone: phoneNumber
            }

            // 如果有订阅权限，传递openid
            if (hasSubscribePermission && userOpenId) {
                // 最后一次验证openid
                if (userOpenId.startsWith('mock_')) {
                    console.log('⚠️ 发现发送时仍然是模拟openid，重新获取真实openid')
                    await getUserOpenId()
                    // 重新获取最新的openid
                    const latestOpenId = Taro.getStorageSync('openid')
                    if (latestOpenId && !latestOpenId.startsWith('mock_')) {
                        requestData.openid = latestOpenId
                        console.log('✅ 使用重新获取的openid:', latestOpenId)
                    } else {
                        console.log('⚠️ 仍然无法获取有效openid，将使用模拟模式')
                    }
                } else {
                    requestData.openid = userOpenId
                }
            }

            const response: any = await api.post('/auth/send-sms', requestData)

            if (response.success) {
                // 根据发送方式显示不同的提示
                if (response.method === 'wechat') {
                    Taro.showToast({
                        title: '验证码已发送到微信通知',
                        icon: 'success'
                    })
                } else {
                    Taro.showToast({
                        title: '验证码发送成功',
                        icon: 'success'
                    })
                }

                // 仅在微信发送失败时显示开发模式弹窗（便于调试）
                if (response.devCode && response.method !== 'wechat') {
                    const modalContent = `验证码：${response.devCode}`

                    setTimeout(() => {
                        Taro.showModal({
                            title: '开发模式',
                            content: modalContent,
                            showCancel: false
                        })
                    }, 1000)
                }

                // 开始60秒倒计时
                setCountdown(60)
            } else {
                throw new Error(response.message || '发送失败')
            }

        } catch (error: any) {
            Taro.showToast({
                title: error.message || '发送失败，请重试',
                icon: 'none'
            })
        } finally {
            setIsLoading(false)
        }
    }

    // 手机号登录
    const handlePhoneLogin = async () => {
        if (!validatePhone(phoneNumber)) {
            Taro.showToast({
                title: '请输入正确的手机号',
                icon: 'none'
            })
            return
        }

        if (!verifyCode || verifyCode.length < 4) {
            Taro.showToast({
                title: '请输入正确的验证码',
                icon: 'none'
            })
            return
        }

        try {
            setIsLoading(true)
            Taro.showLoading({
                title: '登录中...'
            })

            // 调用手机号登录接口，传递openid以支持账号绑定
            const requestData: any = {
                phone: phoneNumber,
                code: verifyCode
            }

            // 如果有openid，传递给后端用于账号绑定
            if (userOpenId) {
                requestData.openid = userOpenId
                console.log('📱 手机号登录携带openid:', userOpenId)
            }

            const response: any = await api.post('/auth/phone-login', requestData)

            if (response.success) {
                // 使用全局状态管理保存登录信息
                if (response.token && response.userInfo) {
                    login(response.userInfo, response.token)
                }

                // 根据绑定类型显示不同的成功提示
                let successMessage = '登录成功'
                if (response.bindingType === 'wechat_to_phone') {
                    successMessage = '已绑定到微信账户'
                } else if (response.bindingType === 'existing_phone') {
                    successMessage = '欢迎回来'
                } else if (response.bindingType === 'new_user') {
                    successMessage = '注册成功'
                }

                console.log(`✅ 手机号登录成功 - 绑定类型: ${response.bindingType}`)

                Taro.showToast({
                    title: successMessage,
                    icon: 'success'
                })

                // 延迟跳转到首页
                setTimeout(() => {
                    Taro.switchTab({
                        url: '/pages/index/index'
                    }).catch(() => {
                        Taro.redirectTo({
                            url: '/pages/index/index'
                        })
                    })
                }, 1500)
            } else {
                throw new Error(response.message || '登录失败')
            }

        } catch (error: any) {
            Taro.showToast({
                title: error.message || '登录失败，请重试',
                icon: 'none'
            })
        } finally {
            setIsLoading(false)
            Taro.hideLoading()
        }
    }

    return (
        <View className="phone-login-container">
            {/* Logo区域 */}
            <View className="logo-section">
                <View className="logo">
                    <Text className="logo-text">新氧</Text>
                </View>
            </View>

            {/* 表单区域 */}
            <View className="form-section">
                {/* 手机号输入 */}
                <View className="input-group">
                    <View className="phone-input-wrapper">
                        <Text className="country-code">+86</Text>
                        <Input
                            className="phone-input"
                            type="number"
                            placeholder="请输入手机号"
                            value={phoneNumber}
                            onInput={handlePhoneInput}
                            maxlength={11}
                        />
                    </View>
                </View>

                {/* 验证码输入 */}
                <View className="input-group">
                    <View className="code-input-wrapper">
                        <Input
                            className="code-input"
                            type="number"
                            placeholder="请输入验证码"
                            value={verifyCode}
                            onInput={handleCodeInput}
                            maxlength={6}
                        />
                        <Button
                            className={`send-code-btn ${countdown > 0 ? 'disabled' : ''}`}
                            onClick={handleSendCode}
                            disabled={countdown > 0 || isLoading}
                        >
                            {countdown > 0 ? `${countdown}秒后重发` : '发送验证码'}
                        </Button>
                    </View>
                </View>

                {/* 登录按钮 */}
                <Button
                    className="login-btn"
                    onClick={handlePhoneLogin}
                    disabled={isLoading}
                >
                    登录
                </Button>
            </View>

            {/* 底部提示 */}
            <View className="bottom-tip">
                <Text className="tip-text">未注册手机号将创建新氧账号</Text>
            </View>
        </View>
    )
}